﻿#region Copyright(C) 2013-2013 NCS Pte. Ltd. All rights reserved.
// ==================================================================================================
// Copyright(C) 2010 NCS Pte. Ltd. All rights reserved.
//
// SYSTEM NAME      : iConnect .Net Application Framework
// COMPONENT ID     : NCS.IConnect.Core.EntLib
// COMPONENT DESC   : Microsoft Enterprise Library Adapter.
//
// CREATED DATE/BY  : 18 Dec 2013 / Jiang Jin Nan
//
// REVISION HISTORY :
// DATE/BY            SR#/CS/PM#/OTHERS       DESCRIPTION OF CHANGE
// ==================================================================================================
#endregion

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using NCS.IConnect.Core.EntLib.Properties;
using NCS.IConnect.Core.Utilities;
using System.Configuration;

namespace NCS.IConnect.Core.IoC.Configuration
{
    /// <summary>
    /// The <see cref="UnityContainerServiceLocator"/> specific configuration element.
    /// </summary>
    public class UnityContainerServiceLocatorData : ServiceLocatorDataBase
    {
        private const string ContainerNamePropertyName = "containerName";

        /// <summary>
        /// Gets or sets the name of the container.
        /// </summary>
        /// <value>
        /// The name of the container.
        /// </value>
        [ConfigurationProperty(ContainerNamePropertyName, IsRequired = false, DefaultValue = "")]
        public string ContainerName
        {
            get { return (string)base[ContainerNamePropertyName]; }
            set { base[ContainerNamePropertyName] = value; }
        }

        /// <summary>
        /// Creates the service locator.
        /// </summary>
        /// <returns>
        /// The created service locator.
        /// </returns>
        public override IServiceLocator CreateServiceLocator()
        {
            UnityContainer container = new UnityContainer();
            UnityConfigurationSection settings;
            if (!ConfigManager.TryGetConfigurationSection<UnityConfigurationSection>(UnityConfigurationSection.SectionName, out settings))
            {
                if (!string.IsNullOrWhiteSpace(this.ContainerName))
                {
                    throw new ConfigurationErrorsException(Resources.ExceptionUnityConainerNotExists.Format((object)this.ContainerName));
                }
                return new UnityContainerServiceLocator(container);
            }

            if (string.IsNullOrWhiteSpace(this.ContainerName))
            {
                settings.Configure(container);
            }
            else
            {
                settings.Configure(container, this.ContainerName);
            }
            return new UnityContainerServiceLocator(container);
        }
    }
}
